<?php
// +----------------------------------------------------------------------
// | View 视图服务
// +----------------------------------------------------------------------
// | * 视图层
// | * 1.查询所有关联表的字段
// | * 2.处理字段（可显示、可编辑、可排序、可分组、可过滤）、还要通过临时字段、字段权限进行判断，组装出view需要的字段
// | * 3.组装view视图的表格列
// +----------------------------------------------------------------------
// | 错误编码头 231xxx
// +----------------------------------------------------------------------

namespace common\service;

use common\exception\LogicException;
use common\model\TaskLibraryViewConfigModel;
use support\ErrorCode;
use support\SingletonTrait;
use think\Exception;

class TaskLibraryViewConfigService
{
    use SingletonTrait;

    /**
     * 修改排序
     * @param $data
     * @return array
     * @throws \Exception
     */
    public function updateSortIndex($data)
    {
        $ids = array_column($data, 'id');
        $viewConfigIds = model(TaskLibraryViewConfigModel::class)->where(['id' => ['IN', $ids]])->column('id');
        $updData = [];
        foreach ($data as $item) {
            if (!in_array($item['id'], $viewConfigIds)) {
                continue;
            }
            $updData[] = [
                'id' => $item['id'],
                'sort_index' => $item['sort_index'],
            ];
        }
        try {
            CommonService::instance('task_library_view_config')->commonBatchUpdate($updData, 'TaskLibraryViewConfig', false);
        } catch (Exception $e) {
            throw new LogicException($e->getMessage(), ErrorCode::UPDATE_TASK_FAIL);
        }
        return [];
    }

    /**
     * @return array
     */
    public function createSortIndex()
    {
        // 查出最大的系统配置id
        $maxSystemData = model(TaskLibraryViewConfigModel::class)
            ->field('id,sort_index')
            ->where(['type' => 'system'])
            ->order('sort_index desc')
            ->find();
        $maxSystemId = $maxSystemData['sort_index'];
        // 修改后面所有的排序+1
        $updateSql = sprintf("UPDATE `%s` %s `sort_index` = `sort_index` + 1 where `id` > %d", 'task_library_view_config', 'SET', $maxSystemId);
        model(TaskLibraryViewConfigModel::class)->execute($updateSql);
        // 再插入新的数据到挪出来的空位置
        return [];
    }

    /**
     * 需求延期单配置
     * @param $param
     * @return array
     * @throws Exception
     */
    public function demandOrderDelayOrderList($param)
    {
        $filter = $param['filter'] ?? [];
        $projectId = $filter['project_id'] ?? 0;
        $taskLibraryViewConfigList = model(TaskLibraryViewConfigModel::class)
            ->where(['type' => 'demand_order_delay_order'])
            ->where($filter)
            ->select();
        $returnData = [];
        // 如果没有配置,则默认展示4条
        if (empty($taskLibraryViewConfigList)) {
            $demandOrderParam = [
                'filter' => [
                    'project_id' => $projectId,
                    'demand_type' => 'demand_order',
                    'module_code' => 'asset'
                ],
                'page' => [
                    1, 4
                ]
            ];
            $demandOrderList = DemandOrderService::getInstance()->getDemandOrderList($demandOrderParam);
            $sortIndex = 1;
            if (!empty($demandOrderList)) {
                foreach ($demandOrderList as $demandOrderItem) {
                    $returnData[] = [
                        'id' => $demandOrderItem['id'],
                        'title' => $demandOrderItem['title'],
                        'sort_index' => $sortIndex++,
                        'config' => [
                            'data_type' => 'demand_order', // 需求单
                        ]
                    ];
                }
            }
        }
        if (!empty($taskLibraryViewConfigList)) {
            foreach ($taskLibraryViewConfigList as $taskLibraryViewConfigItem) {
                $config = json_decode($taskLibraryViewConfigItem['config'] ?? '{}', true);
                $returnData[] = [
                    'id' => intval($config['demand_order_id']) ?? 0,
                    'name' => $taskLibraryViewConfigItem['name'],
                    'sort_index' => $taskLibraryViewConfigItem['sort_index'] ?? 0,
                    'config' => $config
                ];
            }
        }
        return $returnData;
    }
}


